import Footer from '@/components/Footer';
import RightContent from '@/components/RightContent';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { message } from 'antd';
import defaultSettings from '../config/defaultSettings';
import { GLOBAL_CONFIG, LOGIN_PATH, NO_NEED_LOGIN_PATHS } from './constant';
import type { UserRecord } from './DatabaseType/User';
import { getLoginInfo } from './services/user';
import { ResponseCode } from './utils/request';
export { request } from './utils/request';

export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: UserRecord;
  loading?: boolean;
}> {
  // 这里不需要每次从服务端取，可以选择缓存到sessionStorage
  const fetchUserInfo = async () => {
    try {
      const { data, code, message: msg } = await getLoginInfo();
      if (code === ResponseCode.Fail) {
        message.error(msg);
        return undefined;
      }
      return data;
      // 一般401已经被request拦截了
    } catch (error) {
      return undefined;
    }
  };
  let currentUser: UserRecord | undefined = undefined;
  // 需要登入信息，尝试登入
  if (
    NO_NEED_LOGIN_PATHS.every(
      (path) => !window.location.pathname.includes(path),
    ) ||
    GLOBAL_CONFIG.forceGetLoginInfo
  ) {
    currentUser = await fetchUserInfo();
    GLOBAL_CONFIG.forceGetLoginInfo = false;
  }
  return {
    settings: defaultSettings,
    currentUser: currentUser,
  };
}

export const layout: RunTimeLayoutConfig = ({ initialState, loading }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    footerRender: () => <Footer />,
    onPageChange: () => {
      const pathname = window.location.pathname;
      // 如果没有登录，重定向到 login
      if (
        !initialState?.currentUser &&
        NO_NEED_LOGIN_PATHS.every((path) => !pathname.includes(path)) &&
        // loading的时候等待
        !loading
      ) {
        window.sessionStorage.setItem('LOGIN_FROM', pathname);
        history.push(LOGIN_PATH);
      }
    },
    menuHeaderRender: false,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      return children;
    },
    ...initialState?.settings,
  };
};
